package com.guinea.core.acegi;

import java.util.Properties;

import org.acegisecurity.GrantedAuthority;
import org.acegisecurity.GrantedAuthorityImpl;
import org.acegisecurity.userdetails.UserDetails;
import org.acegisecurity.userdetails.UserDetailsService;
import org.acegisecurity.userdetails.UsernameNotFoundException;
import org.springframework.dao.DataAccessException;

import com.guinea.core.utils.CommonUtils;

public class UserDetailsServiceImpl implements UserDetailsService {
	private AcegiCacheManager acegiCacheManager;

	public void setAcegiCacheManager(AcegiCacheManager acegiCacheManager) {
		this.acegiCacheManager = acegiCacheManager;
	}
	public UserDetails loadUserByUsername(String username)
			throws UsernameNotFoundException, DataAccessException {
		//超级管理员
		if("admin".equals(username)){
			Properties p = CommonUtils.loadAppProperties();
			GrantedAuthority[] authorities = new GrantedAuthority[]{new GrantedAuthorityImpl("admin")};
			UserDetails ud = new UserDetailsImpl(new Long(0), "admin","超级管理员",
					p.getProperty("admin.password"), authorities);
			return ud;
		}

		acegiCacheManager.initUserCache();
		//当用户数量级变大后，需要先取缓存，再取数据库
//        List users = userManager.getUsersByName(username);
//        if (users == null || users.isEmpty()) {
//            throw new UsernameNotFoundException("user '" + username + "' not found...");
//        } else {
//        	User user = (User)users.get(0);
//        	GrantedAuthority[] authorities = role2authorities(user.getRoles());
//            return new org.acegisecurity.userdetails.User(user.getName(), user
//    				.getPassword(), true, true, true, true, authorities);
//        }
		UserDetails u = acegiCacheManager.getUserCache().getUserFromCache(username);
		return u;
	}

}
